import { ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { Subscription } from 'rxjs';
import { FormService } from '@core/services/form.service';
import { deepClone } from '../../utils/utils';
import { ApesContextMenuService } from '@shared/ag-grid-ext/context-menu';
import { AssemblyDrawingViewService } from '@core/services/assemblyDrawing/assemblyDrawing.view.service';
import { AssemblyDrawingService } from '@core/services/assemblyDrawing/assemblyDrawing.service';
import { ApesModalRef, ApesModalService } from '@shared/apes/modal';
import { AssemblyDrawingDialogComponent } from './assemblyDrawing-dialog.component';
import { AssemblyDrawingInfoDialogComponent } from './assemblyDrawing-infoDialog.component';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { SearchService } from '@core/services/search.service';
import { ApesDialogCascaderComponent } from '@shared/dialog-cascader';
import { UserAuthService } from '@core/services/user-auth.service';

@Component({
  selector: 'apes-assembly-drawing',
  templateUrl: './assemblyDrawing.component.html',
  styleUrls: ['./assemblyDrawing.component.scss'],
})

export class AssemblyDrawingComponent implements OnInit, OnDestroy {

  isLoading: boolean = false; // 查询中动画

  changeShowTypeSubscription: Subscription;       // 改变显示类型
  controlShowSubscription: Subscription;          // 控制显示
  imgSelectSubscription: Subscription;            // 热点图数据
  menuSubscription: Subscription;                 // 主组数据
  mainMenuSubscription: Subscription;             // 当前主菜单数据
  subMenuSubscription: Subscription;              // 当前子菜单数据
  showLoadingStepSubscription: Subscription;      // 加载步骤
  btnLoadingSubscription: Subscription;           // 上下组按钮加载状态
  carInfoChangeSubscription: Subscription;        // 弹框配置
  searchLoadingSubscription: Subscription;        // 查询弹框按钮配置
  searchDataSubscription: Subscription;           // 查询配件数据
  searchPriceSubscription: Subscription;          // 查询价格前置数据
  searchSanTouInquireSubscription: Subscription;  // 查询三头六臂数据
  searchSanTouPriceSubscription: Subscription;    // 查询三头六臂配件数据

  showType: number = 1;                      // 主界面显示模式
  switchValue: boolean = false;              // 查询界面显示模式
  carParam;

  // 车架号 配置车型 厂牌模式
  vin: string = '';
  vehicleConfig: string = '';
  brandName: string = '';

  // epc编码 epc版本模式
  epcId: string = '';
  epcVersion: string = '';


  // 关键词 配件名
  partsName: any = '';

  // 搜索框配置
  searchModel: any = { relationType: 'no_auto' };
  searchType: any = 'no_auto';
  searchTypeList: any[] = [
    // { 'id': 'no_auto', 'name': '匹配模式(标准配件)' },
    // { 'id': 'blurry', 'name': '匹配车型(模糊搜索)' },
    { 'id': 'no_auto', 'name': '匹配车型' },
    { 'id': 'yes', 'name': '不匹配' },
  ];
  searchField: FormlyFieldConfig[] = [];
  noAutoType: FormlyFieldConfig[] = [
    {
      key: 'categoryTemp',
      type: 'conditionInput',
      templateOptions: {
        label: '',
        placeholder: '请选择标准配件名称',
        config: {
          api: 'cm.category.findAllByKeyword',
          dialogType: 'cascader',
          downFormatter: 'value.tagName',
          downRightFormatter: 'value.name',
          operators: ['LIKE'],
          searchFormId: 'cm.classify.findAll',
          tooltipFormatter: '点击"放大镜"可按分类检索到配件名称',
          type: 'select',
          valueFormatter: '"[" + value.id + "]" + value.name',
          // width: '500',
        },
        hide: 'true',
        domain: '{"filters":[{"field":"matchCProduct","operator":"EQ","value":true}],"groups":[{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"},{"field":"categoryTags.name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}],"operator":"and"}',
        divCol: 24,
        lblCol: 0,
        inputCol: 24,
      },
    },
  ];
  yesType: FormlyFieldConfig[] = [
    {
      key: 'productTemp',
      type: 'conditionInput',
      templateOptions: {
        label: '',
        placeholder: '请输入配件名称/OE号/商品编码/商品名称进行搜索',
        config: {
          operators: ['LIKE'],
          type: 'string',
        },
        divCol: 24,
        lblCol: 0,
        inputCol: 24,
      },
    },
  ];
  blurryType: FormlyFieldConfig[] = [
    {
      key: 'blurryTemp',
      type: 'conditionInput',
      templateOptions: {
        label: '',
        placeholder: '请输入配件名称/OE号搜索',
        config: {
          operators: ['LIKE'],
          type: 'string',
        },
        divCol: 24,
        lblCol: 0,
        inputCol: 24,
      },
    },
  ];
  isQuery: boolean = false;                  // 能否解析
  size: any = 10;
  page: any = 0;
  searchLoading: boolean = false;


  keywordAndMenuNameDisabled = true;         // 界面控制
  searchDisabled: boolean = true;            // 查询控制
  showDisabled: boolean = true;              // 界面切换控制
  showHidden: boolean = false;               // 隐藏显示价格


  // 装配图
  model: any = {};                           // 服务方案原型
  cacheData: any = {};                       // 当前车型信息
  modelInfo: any = {};                       // 配置车型数据
  menuData: any[] = [];                      // 菜单数据
  mainMenuData: any = {};                    // 当前主菜单数据
  subMenuData: any = {};                     // 当前子菜单数据
  searchData: any = {};                      // 查询配件数据
  showLoadingStep: any = 0;                  // 查询步骤
  showLoadingText: any = '开始查询解析中，请稍后...';     // 查询文字
  isLastLoading: boolean = false;           // 上一组查询中
  isNextLoading: boolean = false;           // 下一组查询中
  dialogRef: ApesModalRef;                            // 弹框
  shoppingVisible: boolean = false;         // 购物车显示
  selectAll: boolean = false;               // 购物车全选
  selectData: any = {};                      // 选中购物车数据
  heatMapData: any = [];                     // 当前热点图数据
  previousPageUrl: any = '';                 // 上一页地址
  custom: any = 'servicePlan';                     // 使用插件页面 servicePlan，lossQuotation
  shoppingData: any[] = [];
  publicPage: boolean = false;               // 是否公共页面
  filterResultData: any[] = [];              // 过滤数据

  constructor(
    private apiService: ApiService,
    private msg: ApesMessageService,
    private assemblyDrawingViewService: AssemblyDrawingViewService,
    private assemblyDrawingService: AssemblyDrawingService,
    protected formService: FormService,
    private contextService: ApesContextMenuService,
    private modalService: ApesModalService,
    private searchService: SearchService,
    private userAuthService: UserAuthService,
    private cd: ChangeDetectorRef,
  ) {

  }

  ngOnInit(): void {

    this.initData();

    this.initViewData();

    this.initSearchData();

  }

  ngOnDestroy(): void {
    this.changeShowTypeSubscription.unsubscribe();
    this.controlShowSubscription.unsubscribe();
    this.showLoadingStepSubscription.unsubscribe();
    this.imgSelectSubscription.unsubscribe();
    this.menuSubscription.unsubscribe();
    this.mainMenuSubscription.unsubscribe();
    this.subMenuSubscription.unsubscribe();
    this.btnLoadingSubscription.unsubscribe();
    this.carInfoChangeSubscription.unsubscribe();
    this.searchLoadingSubscription.unsubscribe();
    this.searchDataSubscription.unsubscribe();
    this.searchPriceSubscription.unsubscribe();
    this.searchSanTouInquireSubscription.unsubscribe();
    this.searchSanTouPriceSubscription.unsubscribe();
  }

  toggle(type: number) {
    if (type == 2 || type == 3) {
      if (type == 2) {
        // this.assemblyDrawingViewService.subgroupChange$.next(this.menuData);
        if (!this.mainMenuData.hasOwnProperty('code') && this.mainMenuData.hasOwnProperty('name')) {
          this.assemblyDrawingViewService.subgroupChange$.next(this.menuData);
          this.assemblyDrawingViewService.mainMenuChange$.next({});
        }
      }
      if (type == 3) {
        this.assemblyDrawingViewService.controlShowBtn$.next(true);
      }
      this.assemblyDrawingViewService.subMenuChange$.next({});
      this.showType = 1;
    } else if (type == 1) {
      this.showType = 2;
    }

    // if (type == 1) {
    //   this.assemblyDrawingViewService.subMenuChange$.next({});
    // }
    // this.showType = type;
  }

  black() {
    this.operationLog('quit');
    let params = {
      'OAInterface': false,
      'formId': this.previousPageUrl,
      'routerTask': true,
      'api': 'cad',
      'body': this.model,
    };
    this.formService.navigateToForm(params);
  }

  showTypeText() {

    let text = '';
    switch (this.showType) {
      case 1:
        text = '详情';
        break;
      case 2:
        text = '列表';
        break;
      case 3:
        text = '首页';
        break;
    }
    return text;
  }

  checkBlack() {
    if (this.shoppingData.length > 0) {
      this.modalService.confirm({
        apesTitle: '是否返回服务方案?',
        apesContent: '当前配件篮存在已选配件，返回将全部清空，请确认！',
        apesOkText: '确认',
        apesOnOk: () => {
          this.black();
        },
        apesCancelText: '取消',
        // apesOnCancel: () => {}
      });
    } else {
      this.black();
    }

  }

  checkShowHidden() {
    this.showHidden = !this.showHidden;
  }

  parseFailure(msg?) {
    let title = msg ? msg : '不支持当前车型vin码解析！';

    this.dialogRef = this.modalService.info({
      apesTitle: '<i>' + title + '</i>',
      apesMaskClosable: false,
      apesOkText: '返回',
      apesOkType: 'primary',
      apesOnOk: () => {
        this.dialogRef.close();
        setTimeout(() => {
          this.isQuery = false;
          if (this.publicPage) {
            this.black();
          }
        }, 500);
      },
    });
  }

  lastSubgroup() {
    this.isLastLoading = true;
    this.assemblyDrawingService.lastSubgroup$.next({});
  }

  nextSubgroup() {
    this.isNextLoading = true;
    this.assemblyDrawingService.nextSubgroup$.next({});
  }


  /**
   *  装配图函数 start
   */

  // 打开购物车
  // openShoppingCart() {
  //   this.shoppingVisible = true;
  // }

  // 关闭购物车
  closeShoppingCart() {
    this.shoppingVisible = false;
    this.shoppingData.forEach((row) => {
      row['selected'] = false;
    });
  }

  // 点击全选
  // clickSelectAll() {
  //   this.shoppingData.forEach((row) => {
  //     row['selected'] = this.selectAll;
  //   });
  // }

  // 检查全选
  // checkSelectAll() {
  //   let selectAll = true;
  //   this.shoppingData.forEach((row) => {
  //     if (row['selected'] == false) {
  //       return selectAll = false;
  //     }
  //   });
  //   this.selectAll = selectAll;
  // }

  // 检查数量
  // checkNum(i) {
  //   let num = this.shoppingData[i].orderQuantity;
  //   this.shoppingData[i].orderQuantity = parseInt(num);
  // }

  // 修改数量
  setNum(i, type) {
    let num;
    if (type == 'add') {
      num = this.shoppingData[i].orderQuantity + 1;
    } else if (type == 'prune') {
      num = this.shoppingData[i].orderQuantity - 1;
    }
    if (num <= 0) {
      num = 1;
    }
    this.shoppingData[i].orderQuantity = parseInt(num);
  }

  // 删除
  deleteShop(i) {
    this.shoppingData.splice(i, 1);
  }

  // 已选商品数
  partsNumber() {
    let num = 0;
    this.shoppingData.forEach((row) => {
      // if (row['selected'] == true) {
      num += 1;
      // }
    });
    return num;
  }

  // 跳转购物车页面
  goShoppingCar() {
    let resultData = {
      model: this.model,
      cacheData: this.cacheData,
      menuData: this.menuData,
      modelInfo: this.modelInfo,
      subMenuData: this.subMenuData,
      shoppingData: [{
        vin: this.cacheData.vin,
        QCCPMC: this.cacheData.QCCPMC,
        parts: this.shoppingData,
      }],
      currentUrl: this.previousPageUrl,
      custom: this.custom,
      searchModel: this.searchModel,
      searchData: this.searchData,
      showType: this.showType,
      searchType: this.searchType,
      isQuery: this.isQuery,
      batchNumber: this.batchNumber,
    };
    let api = 'assemblyDrawing/shopCar';
    let config = { OAInterface: false };
    this.contextService.openContextLink(resultData, api, config);
  }

  // 订阅动态数据
  initData() {

    // 加载步骤
    this.showLoadingStepSubscription = this.assemblyDrawingViewService.showLoadingStep$.subscribe((res) => {
      let step: any;
      let msg: any;
      if (typeof res === 'object') {
        step = res['step'];
        msg = res['msg'];
      } else {
        step = res;
      }
      switch (step) {
        case 0:
          this.showLoadingText = '查询是否服务车型中，请稍后...';
          break;
        case 1:
          this.showLoadingText = '查询解析车型配置中，请稍后...';
          break;
        case 2:
          this.showLoadingText = '查询解析VIN中，请稍后...';
          break;
        case 3:
          this.showLoadingText = '获取主组数据中，请稍后...';
          break;
        case 4:
          this.showLoadingText = '解析数据中，请稍后...';
          setTimeout(() => {
            this.isLoading = false;
            this.isQuery = true;
            this.baseDataChange('init');
            this.operationLog('enter');
          }, 1000);
          break;
        case 5:
          this.showLoadingText = '解析完成，请稍后...';
          setTimeout(() => {
            this.isLoading = false;
            this.isQuery = false;
            if (msg || (!msg && this.publicPage)) {
              this.parseFailure(msg);
            }
            this.baseDataChange('init');
            this.operationLog('enter');
          }, 1000);
          break;
        default:
          this.showLoadingText = '开始查询解析中，请稍后...';
      }
      this.showLoadingStep = step;
    });

    // 车辆查询数据
    this.assemblyDrawingViewService.cacheDataChange$.subscribe((data) => {
      if (data) {
        this.cacheData = data;
      }
    });

    // 配置车型数据
    this.assemblyDrawingViewService.modelInfoChange$.subscribe((data) => {
      if (data) {
        this.modelInfo = data;
      }
    });

    // 车型配置
    this.carInfoChangeSubscription = this.assemblyDrawingViewService.carInfoChange$.subscribe((data) => {
      this.filterInfoData(data);
    });

    // 改变显示类型
    this.changeShowTypeSubscription = this.assemblyDrawingViewService.showTypeChange$.subscribe((data: number) => this.showType = data);

    // 热点图数据
    this.imgSelectSubscription = this.assemblyDrawingViewService.imgSelectChange$.subscribe((data: any) => {
      if (data && data.imgs) {
        this.heatMapData['imgs'] = data.imgs;
      } else {
        this.heatMapData = [];
      }
    });

    // 主组数据
    this.menuSubscription = this.assemblyDrawingViewService.menuChange$.subscribe((data: any) => {
      if (data && data.length != 0) {
        this.menuData = data;
      } else {
        this.menuData = [];
      }
    });

    // 当前主菜单数据
    this.mainMenuSubscription = this.assemblyDrawingViewService.mainMenuChange$.subscribe((data: any) => {
      if (data) {
        this.mainMenuData = data;
      } else {
        this.mainMenuData = {};
      }
    });

    // 当前子菜单数据
    this.subMenuSubscription = this.assemblyDrawingViewService.subMenuChange$.subscribe((data: any) => {
      if (data) {
        this.subMenuData = data;
      } else {
        this.subMenuData = {};
      }
    });

    // 控制显示
    this.controlShowSubscription = this.assemblyDrawingViewService.controlShowBtn$.subscribe((data: boolean) => {
      this.showDisabled = data;
    });

    // 控制查询按钮
    this.searchLoadingSubscription = this.assemblyDrawingViewService.searchLoadingBtn$.subscribe((data: boolean) => {
      this.searchLoading = data;
      if (!data) {
        this.baseDataChange('end');
      }
    });

    // 控制上下组按钮
    this.btnLoadingSubscription = this.assemblyDrawingViewService.partsListLoadingChange$.subscribe((data) => {
      if (!data) {
        this.isLastLoading = false;
        this.isNextLoading = false;
      }
    });

    // 查询配件数据
    this.searchDataSubscription = this.assemblyDrawingViewService.searchDataChange$.subscribe((data) => {
      let resultType: any = '';
      let resultData: any = null;
      if (data) {
        if (data.hasOwnProperty('apes')) {
          this.searchData['apes'] = data['apes'];
          this.searchData['apesDisplay'] = data['apesDisplay'] ? data['apesDisplay'] : data['display'];
          this.queryStock = data['queryStock'];
          resultType = this.queryStock ? '库存' : '通用';
          resultData = data['apes'].content.length != 0;
        }
        if (data.hasOwnProperty('data')) {
          this.searchData['data'] = data['data'];
          this.searchData['dataDisplay'] = data['dataDisplay'] ? data['dataDisplay'] : data['display'];
          resultType = '兆配';
          resultData = data['data'].items.length != 0;
        }
        this.baseDataChange('end');
        this.operationLog('inquire', resultType, resultData);
      }
    });

    this.searchPriceSubscription = this.assemblyDrawingViewService.searchPriceChange$.subscribe((data) => {
      this.searchData['price'] = data;
    });

    this.searchSanTouInquireSubscription = this.assemblyDrawingViewService.searchSanTouInquireChange$.subscribe((data) => {
      this.searchData['sanTou'] = data;
    });

    this.searchSanTouPriceSubscription = this.assemblyDrawingViewService.searchSanTouPriceChange$.subscribe((data) => {
      if (data && data['content'].length != 0) {
        this.searchData['sanTou']['content'].forEach((item) => {
          data['content'].forEach((d) => {
            if (item['productNumber'] == d['productNumber']) {
              item['priceSuggested'] = d['priceSuggested'];
            }
          });
        });
      }
    });
  }

  // 初始化视图数据
  initViewData() {
    if (this.formService.formData.hasOwnProperty('key')) {
      // console.log(this.formService.formData['key']);
      this.initBaseData();
      if (this.formService.formData['key'].conditionModel) {
        this.model = deepClone(this.formService.formData['key'].conditionModel);
        this.previousPageUrl = this.formService.formData['key'].currentUrl;
        if (this.formService.formData['key'].hasOwnProperty('custom')) {
          this.custom = this.formService.formData['key'].custom;
        }
        if (this.model.hasOwnProperty('publicPage')) {
          this.publicPage = true;
        }
        if (this.model['customerCar']) {
          this.isLoading = true;
          this.cacheData = deepClone(this.model['customerCar']);
          // 多选：honda,LHGCP168288027506
          // 单选：bjhd,LBEMDAFC7FZ559656
          // 本地：vw,LSVUC20T1H2164501,GAL0144A00040
          // 数据：CCG,LBV5S1105FSK54978,CBM0220A00450
          // 同一配件多次出现：LJDMAA227E0474231
          // this.cacheData['brandCode'] = 'bjhd';
          // this.cacheData['vin']='LFV2A21K3E4292575';
          // this.cacheData['PZCXID'] = 'GAL0144A00040';

          this.assemblyDrawingService.startParse(this.cacheData, this.model, this.publicPage);
        } else {
          this.msg.error('请提供配置车型信息');
        }
      } else if (this.formService.formData['key'].baseData) {
        let baseData = deepClone(this.formService.formData['key'].baseData);
        this.model = baseData['model'];
        this.cacheData = baseData['cacheData'];
        this.menuData = baseData['menuData'];
        this.modelInfo = baseData['modelInfo'];
        this.previousPageUrl = baseData['currentUrl'];
        this.custom = baseData['custom'];
        this.batchNumber = baseData['batchNumber'];
        this.shoppingData = this.formService.formData['key'].shoppingData[0].parts;
        this.isQuery = baseData.isQuery;
        if (baseData.showType == 3) {
          this.showType = baseData.showType;
          this.showDisabled = false;
          this.searchType = baseData.searchType;
          this.searchModel = baseData.searchModel;
          setTimeout(() => {
            this.searchTypeChange(baseData.searchType, false);
            this.assemblyDrawingViewService.searchDataChange$.next(baseData.searchData);
          }, 500);
        }
        // else if (baseData.showType == 2) {
        //   this.showType = baseData.showType;
        //   this.subMenuData = baseData.subMenuData;
        //   this.menuData = baseData.menuData;
        //   setTimeout(() => {
        //     this.assemblyDrawingService.selectSubgroup$.next(baseData.subMenuData);
        //   }, 500);
        // }
        setTimeout(() => {
          this.assemblyDrawingViewService.modelInfoChange$.next(this.modelInfo);
          let menuData = baseData['menuData'];
          this.assemblyDrawingViewService.menuChange$.next(menuData);
          this.assemblyDrawingViewService.subgroupChange$.next(menuData);
        }, 500);
        this.isLoading = false;
      }
      delete this.formService.formData['key'];
    } else {
      if (!this.brandName.trim() || !this.vin.trim() || !this.vehicleConfig.trim()) {
        this.msg.error('车架号,配置车型编码,汽车厂牌名称都不允许为空');
      }
    }

  }

  // 初始化原始数据
  initBaseData() {
    this.model = {};
    this.cacheData = {};
    this.modelInfo = {};
    this.menuData = [];
    this.showLoadingStep = 0;
    this.showLoadingText = '开始查询解析中，请稍后...';
    this.heatMapData = {};
    this.searchData = {};
    this.publicPage = false;
    this.searchDisabled = true;
  }

  // 初始化查询数据
  initSearchData() {
    this.searchField = this.noAutoType;
    // this.searchTypeList = [
    //   { 'id': 'no_auto', 'name': '匹配模式(标准配件)' },
    //   { 'id': 'blurry', 'name': '匹配车型(模糊搜索)' },
    //   { 'id': 'yes', 'name': '不匹配' },
    // ];
    // this.searchType = 'no_auto';
    // this.searchModel = { relationType: 'no_auto' };

    this.baseDataChange('init');
  }

  baseDataChange(status) {
    // status: init | change | loading | end
    this.searchBaseData = {
      searchType: this.searchType,
      isQuery: this.isQuery,
      queryStock: this.queryStock,
      status: status,
      custom: this.custom,
      hasBelongDept: this.model.hasOwnProperty('belongDept'),
    };
  }

  // 选中订购
  orderParts(data) {
    // console.log('当前热点图', this.heatMapData);
    if (!data.hasOwnProperty('isMatchParts')) {
      data['isMatchParts'] = true;
    }

    if (data.parts.length == 0 && !data.hasOwnProperty('subGroupName')) {
      data['subGroupName'] = this.subMenuData['name'];
    }

    let urls = [];
    let url;
    if (data.hasOwnProperty('imageSN')) {
      urls = this.filterImgData(data['imageSN']);
    }
    if (urls.length != 0) {
      url = urls[0];
    }

    let parts = {
      ...data,
      'selected': true,
      'url': url,
      'urls': urls,
    };
    // console.log('当前选中数据', parts);
    if (parts['isMatchParts']) {
      if (parts['parts'].length > 1 || (parts['ispartOrientation'] && parts['parts'].length == 0)) {
        this.filterPartsData(parts);
      } else {
        this.pushShopingCar(parts);
      }
    } else {
      this.pushShopingCar(parts);
    }

  }

  // 处理热点图数据
  filterImgData(sn) {
    let _sn = sn.replace(/[()]/g, '');
    let urls = [];

    if (this.heatMapData['imgs'].length != 0) {
      this.heatMapData['imgs'].forEach((img) => {
        let points = [];
        img['points'].forEach((p) => {
          if (p['sn'] == _sn) {
            points.push(p);
          }
        });

        if (points.length == 0) return;

        let name = this.interceptionName(img['url']);
        let url = {
          'fileName': name,
          'size': 0,
          'name': name,
          'id': '',
          'type': 'image/jpeg',
          'url': img['url'],
          'points': points,
        };
        urls.push(url);
      });
    }

    return urls;
  }

  // 选中配件弹框
  filterPartsData(parts) {
    // console.log(parts);
    let dialog;
    const openDialog = dialog ? dialog : AssemblyDrawingDialogComponent;
    const dialogRef = this.modalService.create({
      apesWidth: 500,
      apesMaskClosable: false,
      apesTitle: '请选择配置',
      apesContent: openDialog,
      apesComponentParams: { modelData: parts },
      apesFooter: [
        {
          label: '取消',
          type: 'default',
          onClick: () => {
            dialogRef.close();
          },
        },
        {
          label: '确定',
          type: 'primary',
          disabled: (componentInstance) => {
            let resData = componentInstance['resData'];
            let disabled = true;
            if (resData['parts'].length == 1 || resData['positionConfirma']) {
              disabled = false;
            }
            return disabled;
          },
          onClick: (componentInstance) => {
            let resData = componentInstance['resData'];
            this.pushShopingCar(resData);
            dialogRef.close();
          },
        },
      ],
    });
  }

  // 选中配置弹框
  filterInfoData(data) {
    // console.log(data);
    let dialog;
    const openDialog = dialog ? dialog : AssemblyDrawingInfoDialogComponent;
    const dialogRef = this.modalService.create({
      apesWidth: 500,
      apesMaskClosable: false,
      apesTitle: '该车有多个配置型号，请自行选择下列对应配置',
      apesContent: openDialog,
      apesComponentParams: { modelData: data },
      apesFooter: [
        {
          label: '确定',
          type: 'primary',
          disabled: (componentInstance) => {
            let selectorId = componentInstance['selectorId'];
            let disabled = true;
            if (selectorId != '') {
              disabled = false;
            }
            return disabled;
          },
          onClick: (componentInstance) => {
            let resData = componentInstance['resData'];
            this.assemblyDrawingService.analysisVIN(resData);
            dialogRef.close();
          },
        },
      ],
    });
  }

  // 查询购物车商品
  checkParts(parts) {
    let api = 'cm.product.checkDwgProduct';
    let sub = deepClone(parts);
    if (sub.hasOwnProperty('highLowconfig')) {
      sub.oldPartCode = sub.partCode;
      sub.partCode = this.modelInfo['CXPJID'];
    }
    let data = {
      fitting: [sub],
    };
    this.apiService.post(api, data).subscribe((body) => {
      // console.log(body);
    });
  }

  // 添加进购物车
  pushShopingCar(parts) {
    if (parts['highLowconfig']) {
      // this.msg.info('该配件存在高低配，请注意选件', { apesDuration: 2000 });
    }

    this.checkParts(parts);

    if (parts.hasOwnProperty('priceFlag') && !parts.priceFlag) {
      this.msg.info('商品 ' + parts.partCode + ' 未找到价格，请在提交服务方案前联系采购完善价格');
    }

    let add = true;
    this.shoppingData.forEach((listData) => {
      if (listData.partCode == parts.partCode) {
        if (listData.parts.length > 0) {
          if (listData.parts[0]['PJMCID'] == parts.parts[0]['PJMCID']) {
            listData.orderQuantity += 1;
            add = false;
          }
        } else {
          listData.orderQuantity += 1;
          add = false;
        }
      }
    });


    if (add) {
      this.msg.success('已添加成功进配件篮');
      this.shoppingData.unshift(parts);
      // this.compileTodo(parts);
    } else {
      this.msg.success('已添加配件数量');
    }

  }

  refreshData() {
    this.isLoading = true;
    this.inputValue = '';
    this.assemblyDrawingService.startParse(this.cacheData, this.model, this.publicPage);
    // this.operationLog('refresh');
  }

  // 处理热点图名称
  interceptionName(name) {
    let arr = name.split('/');
    let res = arr[arr.length - 1];
    return res;
  }

  // 推送纠错待编译待办
  compileTodo(data) {
    // console.log(data);

    let urls = this.filterImgData(data['imageSN']);
    let url;
    if (urls.length != 0) {
      url = urls[0];
    }

    let arr = [];
    data.parts.forEach((res) => {
      arr.push({ id: res['PJMCID'], name: res['PJMC'] });
      // res['id']= res['PJMCID'];
      // res['name']= res['PJMC'];
    });

    let parts = {
      ...data,
      'selected': true,
      'url': url,
      'urls': urls,
    };

    let api = 'autoparts.epcPartCodeParse.create';
    let postData = {
      vin: this.cacheData['vin'],
      pzcxid: this.cacheData['PZCXID'],
      qccpmc: this.cacheData['QCCPMC'],
      epcVersion: this.cacheData['epcVersion'] ? this.cacheData['epcVersion'] : '暂缺',
      menuName: parts['subGroupName'] ? parts['subGroupName'] : this.subMenuData['name'],
      partCode: parts['partCode'],
      partName: parts['partName'],
      imageSN: parts['imageSN'],
      imageUrl: parts['urls'],
      remark: parts['remark'],
      dept: this.model['saleDept'],
      categories: arr,
      errorFlag: true,
    };
    console.log('推送纠错待编译零件', postData);
    this.apiService.post(api, postData).subscribe((body) => {
      console.log('推送结果', body);
    });

  }

  //
  goToMenu(type) {
    this.showType = 1;
    this.assemblyDrawingViewService.controlShowBtn$.next(true);
    this.assemblyDrawingViewService.subMenuChange$.next({});
    if (type == 'mainMenu') {
      this.assemblyDrawingViewService.subgroupChange$.next(this.menuData);
      this.assemblyDrawingViewService.mainMenuChange$.next({});
    } else if (type == 'subMenu') {
      if (!this.mainMenuData.hasOwnProperty('code') && this.mainMenuData.hasOwnProperty('name')) {
        this.assemblyDrawingViewService.subgroupChange$.next(this.menuData);
        this.assemblyDrawingViewService.mainMenuChange$.next({});
      }
      // this.assemblyDrawingViewService.subMenuChange$.next({});
    }

  }

  // 查询配件名称
  searchPartsName() {

    if (this.partsName != '') {
      let data = { 'keywords': this.partsName };
      this.assemblyDrawingService.searchParts(data);
    } else {
      this.msg.error('请输入配件名称');
    }
  }

  filterName(value) {
    let name = '';
    if (value) {
      name = value.replace(/\$\$/g, ';');
    }
    return name;
  }

  searchTypeChange(value, init) {
    let err = '';
    this.searchDisabled = true;
    if (value == 'no_auto') {
      this.searchField = this.noAutoType;
    } else if (value == 'yes') {
      this.searchField = this.yesType;
      this.searchDisabled = false;
    } else if (value == 'blurry') {
      this.searchField = this.blurryType;
      if (!this.isQuery) {
        err = '该车辆暂无装配图，无法使用模糊搜索，请选择其他模式进行搜索！';
      }
    }
    if (init) {
      this.searchModel = {
        relationType: value,
      };
      this.inputValue = '';
      this.baseDataChange('init');
    } else {
      this.baseDataChange('end');
    }
    this.partsTag = [];
    this.assemblyDrawingViewService.showSearchIntelligent$.next(value);
    if (err != '') {
      this.msg.error(err);
    }
  }

  // 查询匹配配件名称
  searchMatchPartsName() {
    // console.log(this.searchModel);
    this.partsName = '';
    this.queryStock = true;
    let data = this.integrateData(this.isQuery, this.page, this.queryStock);
    let err = this.showSearchType(data);
    if (this.partsName != '' && err == '') {
      this.baseDataChange('loading');
      this.operationLog('inquire');
      this.searchData = {};
      this.assemblyDrawingService.searchMatchParts(data, this.searchType);
      this.assemblyDrawingViewService.mainMenuChange$.next({});
      this.assemblyDrawingViewService.subMenuChange$.next({});
      this.assemblyDrawingViewService.subgroupChange$.next(this.menuData);
    } else {
      this.msg.error(err);
    }
  }

  showSearchType(data) {
    // console.log(data);
    let err = '';
    if (this.partsName == '') {
      err = '请输入配件名称！';
    }
    if (!this.isQuery && data.relationType == 'blurry') {
      err = '该车辆暂无装配图，无法使用模糊搜索，请选择其他模式进行搜索！';
    }
    if (this.publicPage && data.relationType == 'yes' && !data.model.hasOwnProperty('belongDept')) {
      err = '当前角色未关联门店，请使用匹配模式搜索! ';
    }
    return err;
  }

  // 查询匹配分页配件数据
  searchMatchParts(param) {
    let page = param.page;
    let queryStock = param.queryStock;
    // this.queryStock = queryStock;
    this.baseDataChange('loading');
    this.operationLog('inquire');
    let data = this.integrateData(false, page, queryStock);
    this.assemblyDrawingService.searchMatchPart(data);
  }

  // 查询三头分页配件数据
  searchSanTouInquireParts(page) {
    let data = this.integrateData(false, page, false);
    this.assemblyDrawingService.searchSanTouInquirePart(data);
  }

  // 查询过滤条件数据
  searchFilterMatchParts(param) {
    let queryStock = param.queryStock;
    let data = param.data;
    this.filterResultData = data;
    this.baseDataChange('loading');
    this.operationLog('inquire');
    let setData = this.integrateData(false, 0, queryStock);
    this.assemblyDrawingService.searchMatchPart(setData);
  }

  integrateData(isQuery, page, queryStock) {
    let key = '';
    let value;
    let text = this.inputValue.replace(/(^\s*)|(\s*$)/g, '');
    // if (this.searchModel.hasOwnProperty('categoryTemp')) { // 标准配件
    //   this.partsName = this.searchModel.categoryTemp_name;
    //   value = this.searchModel.categoryTemp;
    //   key = 'categoryTemp';
    // } else if (this.searchModel.hasOwnProperty('productTemp')) { // 不配件
    //   this.partsName = this.searchModel.productTemp;
    //   value = this.searchModel.productTemp;
    //   key = 'productTemp';
    // } else if (this.searchModel.hasOwnProperty('blurryTemp')) { // 模糊搜索
    //   this.partsName = this.searchModel.blurryTemp;
    //   value = this.searchModel.blurryTemp;
    //   key = 'blurryTemp';
    // }
    if (this.searchType == 'no_auto') {
      this.partsName = text;
      value = this.partsName;
      key = 'categoryTemp';
    } else if (this.searchType == 'yes') {
      this.partsName = text;
      value = this.partsName;
      key = 'productTemp';
      // queryStock = false;
    }
    let tag;
    if (this.partsTag.length != 0) {
      this.partsTag.forEach((p) => {
        if (p.checked) {
          tag = p;
        }
      });
      if (!tag) {
        tag = this.partsTag[0];
        this.partsTag[0].checked = true;
      }
    } else {
      tag = { id: '', name: '' };
    }
    this.currentTag = tag;

    let data = {
      'keywords': this.partsName,
      'model': this.model,
      'isQuery': isQuery,
      'relationType': this.searchModel.relationType,
      'partsType': {
        field: key,
        value: value,
      },
      'partsTag': tag,
      'size': this.size,
      'page': page,
      'queryStock': queryStock, // tag.hasOwnProperty('queryStock') ? tag['queryStock'] : queryStock
      'PZCXID': this.cacheData['PZCXID'],
      'filterCondition': this.filterResultData,
    };
    return data;
  }

  searchChangeLoading: any;
  inputValue: any = '';

  searchBaseData: any = {};
  partsTag: any[] = [];
  currentTag: any;
  partsTagPagination: any = {
    total: 0,
    pageSize: 10,
    currentPage: 0,
    pages: 0,
  };
  showTagMore: boolean = true;
  queryStock: boolean = true;

  searchChange() {
    this.baseDataChange('change');
    if (this.searchType != 'no_auto') return;
    if (this.searchChangeLoading) {
      clearTimeout(this.searchChangeLoading);
      this.searchChangeLoading = null;
    }
    this.searchDisabled = true;
    if (this.inputValue != '' && this.inputValue != undefined) {
      this.searchChangeLoading = setTimeout(() => {
        let data = {
          key: this.inputValue.replace(/(^\s*)|(\s*$)/g, ''),
          page: 0,
          size: 10,
        };
        // console.log('查询开始', this.inputValue);
        let api = 'cm.category.findAccessoryByKeyword';
        this.showType = 3;
        this.showDisabled = false;
        this.assemblyDrawingViewService.searchDataChange$.next(false);
        this.apiService.post(api, data).subscribe((resData) => {
          // console.log('结果', resData);
          if (resData && resData.length != 0) {
            let tag = deepClone(resData.content);
            tag.forEach((t) => {
              t['checked'] = false;
            });
            this.partsTagPagination.currentPage = resData.page;
            this.partsTagPagination.total = resData.total;
            this.partsTagPagination.pages = resData.pages;
            this.partsTag = tag;
            this.showTagMore = resData.page + 1 != resData.pages;
          } else {
            this.partsTagPagination.currentPage = 0;
            this.partsTagPagination.total = 0;
            this.partsTagPagination.pages = 0;
            this.partsTag = [];
          }
          this.searchDisabled = false;
          this.searchChangeLoading = null;
        });
      }, 500);
    } else {
      this.partsTag = [];
    }

  }

  searchChangeIndex() {
    let page = this.partsTagPagination.currentPage + 1;
    let data = {
      key: this.inputValue.replace(/(^\s*)|(\s*$)/g, ''),
      page: page,
      size: 10,
    };
    let api = 'cm.category.findAccessoryByKeyword';

    this.apiService.post(api, data).subscribe((resData) => {
      // console.log('结果', resData);
      let tag = deepClone(resData.content);
      tag.forEach((t) => {
        t['checked'] = false;
      });
      this.partsTagPagination.currentPage = resData.page;
      this.partsTagPagination.total = resData.total;
      this.partsTagPagination.pages = resData.pages;
      this.partsTag = this.partsTag.concat(tag);
      this.showTagMore = resData.page + 1 != resData.pages;
    });
  }

  partsMenuTree() {
    let dialog = ApesDialogCascaderComponent;
    let options = {
      id: 'cm.classify.findAll',
      api: 'cm.category.findAllByKeyword',
    };
    let api = 'cm.classify.findAll';
    this.searchService.openDialog(api, options, (result: any) => {
      if (result && result.length > 0) {
        this.inputValue = result[0]['name'];
        this.searchChange();
      }
    }, dialog ? dialog : null).subscribe();
  }

  batchNumber: any;

  operationLog(status, resultType?, resultData?) {
    // status : enter | inquire | quit | refresh
    if (!this.batchNumber && status == 'enter') {
      this.batchNumber = new Date().getTime();
    }
    // let dept = this.userAuthService.getUserInfoObj().userAccount.post.dept;
    // if (!dept) return;
    let setData = {
      batch: this.batchNumber,                                         // 批次号
      operatingType: { id: status },                                   // 操作类型
      searchType: this.searchType,
      tagText: this.currentTag ? this.currentTag.name : '',
      // userId: '',                                                   // 操作人编码
      // userName: '',                                                 // 操作人名称
      // deptId: dept['id'],                                           // 部门编码
      // deptName: dept['name'],                                       // 部门名称
      license: this.cacheData['carLicense'],                           // 车牌
      vin: this.cacheData['vin'],                                      // 车架号
      inputText: this.inputValue,                                      // 输入文本
      // inventoryCommodity: resData['intelligent'] ? resData['intelligent'] : false,           // 库存商品
      // ZPCommodity: resData['match'] ? resData['match'] : false,                              // 兆配商品
      // universalCommodity: resData['allIntelligent'] ? resData['allIntelligent'] : false,     // 通用商品
      resultType: resultType != undefined ? resultType : null,
      resultData: resultData != undefined ? resultData : null,
    };
    let api = 'apes.behaviorRecord.save';
    // console.log('操作日志' + status, setData);
    this.apiService.post(api, setData).subscribe((resData) => {
      // console.log('操作日志结果', resData);
    });
  }

  showBlackBtn() {
    let showText = '';
    if (this.publicPage) {
      return showText;
    } else {
      if (this.custom == 'lossQuotation') {
        return '定损报价';
      } else {
        return '服务方案';
      }
    }
  }

  showPublicPage() {
    return !this.publicPage;
  }

  checkSearch() {
    let check = true;
    if (this.inputValue != '' && this.inputValue != undefined && !this.searchDisabled && !this.isLoading) {
      check = false;
    }
    return check;
  }
}
